﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace gds_classes
{
    public static class MathMethods
    {
        public static int PowByMod(int a, int K, int p)
        {
            var x = ConvertIntToBin(K);
            int y = 1;
            int t = (int)Math.Log(K, 2);

            List<int> row = new List<int>(t + 1);
            row.Add(a);

            for (int i = 0; i < t; i++)
            {
                row.Add((row[i] * row[i]) % p);
            }

            for (int i = 0; i < t + 1; i++)
            {
                if (x[i] == 1)
                {
                    y *= row[t - i];
                    y %= p;
                }
            }

            return y;
        }

        public static bool IfPrime(int src)
        {
            for (int i = src / 2; i > 2; i--)
            {
                if (src % i == 0)
                {
                    return false;
                }
            }
            return true;
        }

        public static int[] ConvertIntToBin(int src)
        {
            List<int> ret = new List<int>();
            while (src != 0)
            {
                ret.Add((src % 2 == 1) ? 1 : 0);
                src /= 2;
            }
            ret.Reverse();
            return ret.ToArray();
        }

        public static int FindInversion(int c, int m)
        {
            var result = GCD.gcd.GCDAdv(c, m);
            long k = result[1];
            if (k < 0) k += m;
            return (int)k;
        }

        public static int Mod(int dividend, int divisor)
        {
            int result = dividend % divisor;
            if (result < 0)
                result += divisor;
            return result;
        }

    }
}
